package com.dai.spec.gxk.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dai.spec.common.constant.RoleConstants;
import com.dai.spec.common.core.domain.entity.SysUser;
import com.dai.spec.common.enums.ApprovalStatus;
import com.dai.spec.common.enums.CourseStatus;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.SecurityUtils;
import com.dai.spec.common.utils.StringUtils;
import com.dai.spec.common.utils.bean.BeanUtils;
import com.dai.spec.gxk.domain.Course;
import com.dai.spec.gxk.domain.CourseApplication;
import com.dai.spec.gxk.domain.Teacher;
import com.dai.spec.gxk.mapper.CourseApplicationMapper;
import com.dai.spec.gxk.mapper.CourseMapper;
import com.dai.spec.gxk.mapper.TeacherMapper;
import com.dai.spec.gxk.service.CourseApplicationService;
import com.dai.spec.gxk.service.CourseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseApplicationServiceImpl extends ServiceImpl<CourseApplicationMapper, CourseApplication> implements CourseApplicationService {

    private final TeacherMapper teacherMapper;

    private final CourseApplicationMapper courseApplicationMapper;

    private final CourseService courseService;
    private final CourseMapper courseMapper;

    public CourseApplicationServiceImpl(TeacherMapper teacherMapper, CourseApplicationMapper courseApplicationMapper, CourseService courseService, CourseMapper courseMapper) {
        this.teacherMapper = teacherMapper;
        this.courseApplicationMapper = courseApplicationMapper;
        this.courseService = courseService;
        this.courseMapper = courseMapper;
    }

    /**
     * 申请课程
     *
     * @param courseApplication
     * @return
     */
    @Override
    public int saveApplication(CourseApplication courseApplication) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long roleId = user.getRoles().get(0).getRoleId();
        if (!RoleConstants.TEACHER.equals(roleId)) {
            throw new BaseException("当前登录用户不为教师，无权限！");
        }
        //课程余量默认为课程容量
        Long plantCounts = courseApplication.getPlantCounts();
        courseApplication.setLeaveCounts(plantCounts);
        //指派任课老师
        String jobNumber = user.getUserName();

        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teacher::getJobNumber, jobNumber);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        //当前教师申请开课课程，任教老师默认为当前教师
        String teacherName = teacher.getName();
        courseApplication.setTeacherName(teacherName);

        //申请初始状态为待审批状态
        courseApplication.setApprovalStatus(ApprovalStatus.PENDING_APPROVAL.getCode());
        int rows = courseApplicationMapper.insert(courseApplication);
        return rows;
    }

    /**
     * 查询我的课程申请列表
     *
     * @param courseApplication
     * @return
     */
    @Override
    public List<CourseApplication> queryMyApplicationList(CourseApplication courseApplication) {

        checkApplication(courseApplication);
        SysUser user = SecurityUtils.getLoginUser().getUser();

        Long roleId = user.getRoles().get(0).getRoleId();
        if (!RoleConstants.TEACHER.equals(roleId)) {
            throw new BaseException("当前登录用户不为教师，无权限！");
        }
        String jobNumber = user.getUserName();
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teacher::getJobNumber, jobNumber);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        String teacherName = teacher.getName();
        List<CourseApplication> courseApplicationList = queryCourseApplicationList(courseApplication);
        ArrayList<CourseApplication> myApplicationList = new ArrayList<>();
        for (CourseApplication application : courseApplicationList) {
            if (StringUtils.isNotEmpty(teacherName) && teacherName.equals(application.getTeacherName())) {
                myApplicationList.add(application);
            }
        }
        return myApplicationList;
    }

    /**
     * 查询课程申请待审批列表
     *
     * @param courseApplication
     * @return
     */
    @Override
    public List<CourseApplication> queryList(CourseApplication courseApplication) {
        checkApplication(courseApplication);
        List<CourseApplication> courseApplicationList = queryCourseApplicationList(courseApplication);
        ArrayList<CourseApplication> list = new ArrayList<>();
        for (CourseApplication application : courseApplicationList) {
            if (ApprovalStatus.PENDING_APPROVAL.getCode().equals(application.getApprovalStatus())) {
                list.add(application);
            }
        }
        return list;
    }

    private List<CourseApplication> queryCourseApplicationList(CourseApplication courseApplication) {
        LambdaQueryWrapper<CourseApplication> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(courseApplication.getType())) {
            queryWrapper.eq(CourseApplication::getType, courseApplication.getType());
        }
        if (StringUtils.isNotEmpty(courseApplication.getDeliveryType())) {
            queryWrapper.eq(CourseApplication::getDeliveryType, courseApplication.getDeliveryType());
        }
        if (StringUtils.isNotEmpty(courseApplication.getCourseName())) {
            queryWrapper.like(CourseApplication::getCourseName, courseApplication.getCourseName());
        }
        List<CourseApplication> courseApplicationList = courseApplicationMapper.selectList(queryWrapper);
        return courseApplicationList;
    }

    private static void checkApplication(CourseApplication courseApplication) {
//        if (courseApplication == null) {
//            throw new BaseException("申请的课程不能为空");
//        }
//        if (StringUtils.isEmpty(courseApplication.getTeacherName())) {
//            throw new BaseException("课程任课老师不能为空");
//        }
    }

    /**
     * 课程审批
     *
     * @param courseApplication
     * @return
     */
    @Override
    @Transactional
    public int approvalApplication(CourseApplication courseApplication) {
        if (courseApplication == null) {
            throw new BaseException("课程审批为空！");
        }
        if (courseApplication.getId() == null) {
            throw new BaseException("id不能为空");
        }
        int rows = 0;
        String approvalStatus = courseApplication.getApprovalStatus();
        //审批状态为通过
        if (ApprovalStatus.PASS_APPROVAL.getCode().equals(approvalStatus)) {
            //更新课程申请表状态
            LambdaUpdateWrapper<CourseApplication> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CourseApplication::getId, courseApplication.getId())
                    .set(CourseApplication::getApprovalStatus, courseApplication.getApprovalStatus());
            rows = courseApplicationMapper.update(null, updateWrapper);
            //将该课程加入到课程表中
            CourseApplication application = courseApplicationMapper.selectById(courseApplication.getId());
            Course course = new Course();
            course.setStatus(CourseStatus.CLOSE.getCode());
            BeanUtils.copyBeanProp(course, application);
            course.setId(null);
            rows += courseMapper.insert(course);
        } else if (ApprovalStatus.REFUSE_APPROVAL.getCode().equals(approvalStatus)) {
            if (StringUtils.isNotEmpty(courseApplication.getApprovalComment())) {
                //更新课程申请表状态
                LambdaUpdateWrapper<CourseApplication> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(CourseApplication::getId, courseApplication.getId())
                        .set(CourseApplication::getApprovalStatus, courseApplication.getStatus())
                        .set(CourseApplication::getApprovalComment, courseApplication.getApprovalComment());
                rows = courseApplicationMapper.update(null, updateWrapper);
            }
        }
        return rows;

    }
}
